<template>
  <div class="header">
    <div class="header-left">
      <h3 tabindex="0" id="siteName" title="攀枝花学院网络教学平台" @click="toMyCourse" class="header-title">
        攀枝花学院网络教学平台
      </h3>
    </div>
    <div class="header-right">
      <el-col>
        <el-dropdown trigger="click" @command="handleCommand">
          <div>
            <span class="demonstration">
              <!-- 使用 imageUrl 作为 src，确保它是一个字符串 -->
              <el-image :src="imageUrl" fit="cover"></el-image>
            </span>
            <span class="el-dropdown-link">
              {{ userName }} <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="toMyCourse">我的课程</el-dropdown-item>
            <el-dropdown-item command="toMyAccount">账号管理</el-dropdown-item>
            <el-dropdown-item command="toLogin">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </div>
  </div>
</template>

<script>
import { removeToken } from "@/utils/localStorage";
import { joinUserAvatarPath } from "@/utils/joinUserAvatarPath";
import getAvatarUrl from "@/api/getAvatarUrl";
import axios from "@/utils/request";
import socketService from "@/utils/socketService";

export default {
  data() {
    return {
      userId: localStorage.getItem("userId"),
      userName: '',  // 用于存储获取到的用户名
      imageUrl: '',  // 用于存储头像 URL
    };
  },
  methods: {
    getAvatarUrl,
    getUserAvatar: joinUserAvatarPath,
    handleCommand(command) {
      if (command === "toLogin") {
        this.toLogin();
      }
      if (command === "toMyCourse") {
        this.toMyCourse();
      }
      if (command === "toMyAccount") {
        this.toMyAccount();
      }
    },
    toLogin() {
      removeToken();
      localStorage.removeItem("userId"); // 清除用户 ID ，退出登录提示
      socketService.disconnect();
      this.$message({
        message: "退出登录成功",
        center: true,
        type: "success",
        duration: "1500",
        offset: "80",
      });
      this.$router.push("/login");
    },
    toMyCourse() {
      this.$router.push("/studentPage/myCourses").catch((err) => {
        if (err.name !== "NavigationDuplicated") {
          throw err; // 处理除 NavigationDuplicated 以外的错误
        }
      });
    },
    toMyAccount() {
      this.$router.push("/studentPage/myAccount").catch((err) => {
        if (err.name !== "NavigationDuplicated") {
          throw err; // 处理除 NavigationDuplicated 以外的错误
        }
      });
    },
    async getUserName(id) {
      try {
        // 通过 GET 请求获取头像 URL，使用 await 等待异步请求完成
        const response = await axios.get(`http://localhost:3000/getAvatarUrl/${id}`);
        // 获取返回的用户名
        const userName = response.data.userName;
        //console.log(userName);
        this.userName = userName;
        // 获取头像 URL
        const avatarUrl = await this.getAvatarUrl(id);  // 使用异步方法获取头像 URL
        this.imageUrl = avatarUrl;  // 将头像 URL 存入 data 中
      } catch (error) {
        console.error("获取用户名或头像失败:", error);
      }
    },
  },
  created() {
    this.getUserName(this.userId);  // 获取用户名和头像
  },
};
</script>


<style scoped>
.header {
  width: 100%;
  height: 80px;
  background: #FFFFFF;
  box-shadow: 0px 2px 6px 0px rgba(43, 51, 59, 0.06);
  color: #2B333B;
  position: fixed;
  top: 0;
  right: 0;
  left: 10px;
  z-index: 9999;
  display: flex;
  justify-content: space-between;
}
.header-title {
  cursor: pointer;
}
.header-left {
  width: 220px;
  float: left;
  height: 80px;
  display: flex;
  align-items: center;
  display: -webkit-flex;
  display: -ms-flex;
  display: -moz-flex;
  max-width: 60%;
}
.header-right {
  height: 80px;
  width: 220px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中，可选 */
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.demonstration {
  position: relative;
  top: 10px;

}

.demonstration .el-image{
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
}
</style>
